package cn.jingyuan.owl.json.fastjson;

import cn.jingyuan.owl.json.fastjson.serializable.EnumHelper;
import cn.jingyuan.owl.json.fastjson.serializable.ExtendSerializeConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;

public class JsonUtils {

    public static final SerializerFeature[] FORMAT_DEFAULT = {
        SerializerFeature.WriteDateUseDateFormat,
        SerializerFeature.SortField,
        SerializerFeature.WriteMapNullValue
    };

    public static final SerializerFeature[] FORMAT_PRETTY = {
        SerializerFeature.PrettyFormat,
        SerializerFeature.WriteDateUseDateFormat,
        SerializerFeature.WriteMapNullValue
    };

    /**
     * 输出 json 字符串
     * <pre>
     *     美化输出：
     *      日期输出格式：yyyy-MM-dd HH:mm:ss
     *      String null : "key" : null
     * </pre>
     */
    public static String jsonPretty(Object object) {
        return JSON.toJSONString(
            object,
            getInstance(),
            FORMAT_PRETTY
        );
    }

    /**
     * 输出 json 字符串
     * <pre>
     *     输出格式：
     *      日期输出格式：yyyy-MM-dd HH:mm:ss
     *      枚举输出格式：枚举名称
     *      String null : "key" : null
     * </pre>
     */
    public static String json(Object object) {
        return JSON.toJSONString(
            object,
            getInstance(),
            FORMAT_DEFAULT
        );
    }

    public static String json(Object object, List<SerializerFeature> features) {
        return json(object, features, false);
    }

    public static String json(Object object, List<SerializerFeature> features, boolean prettyFormat) {
        if (prettyFormat) {
            features.add(SerializerFeature.PrettyFormat);
        }

        return json(object, getInstance(), features, prettyFormat);
    }

    public static String json(Object object, SerializeConfig config, List<SerializerFeature> features, boolean prettyFormat) {
        if (prettyFormat) {
            features.add(SerializerFeature.PrettyFormat);
        }

        SerializerFeature[] serializerFeatures = (SerializerFeature[]) features.toArray();

        return JSON.toJSONString(object, config, serializerFeatures);
    }

    protected static SerializeConfig getInstance() {
        SerializeConfig config;
        if (EnumHelper.existEnumCoreClass()) {
            config = ExtendSerializeConfig.getInstance();
        } else {
            config = SerializeConfig.getGlobalInstance();
        }

        return config;
    }

}
